package com.ruoyi.service.impl;

import java.math.BigDecimal;
import java.sql.Time;
import java.util.Date;
import java.util.List;
import java.util.Objects;

import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.domain.*;
import com.ruoyi.mapper.*;
import com.ruoyi.system.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.service.IErpInventoryTransferService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 调拨管理Service业务层处理
 *
 * @author zhp
 * @date 2025-08-08
 */
@Service
public class ErpInventoryTransferServiceImpl implements IErpInventoryTransferService {
    @Autowired
    private ErpInventoryTransferMapper erpInventoryTransferMapper;

    @Autowired
    private ErpInventoryTransferDetailMapper erpInventoryTransferDetailMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private ErpOutboundOrderMapper erpOutboundOrderMapper;

    @Autowired
    private ErpInboundOrderMapper erpInboundOrderMapper;

    @Autowired
    private ErpInventoryMapper erpInventoryMapper;

    @Autowired
    private ErpInboundOrderDetailMapper erpInboundOrderDetailMapper;

    @Autowired
    private ErpOutboundOrderDetailMapper erpOutboundOrderDetailMapper;

    @Autowired
    private ErpMaterialMapper erpMaterialMapper;

    /**
     * 查询调拨管理
     *
     * @param id 调拨管理主键
     * @return 调拨管理
     */
    @Override
    public ErpInventoryTransfer selectErpInventoryTransferById(Long id) {
        return erpInventoryTransferMapper.selectErpInventoryTransferById(id);
    }

    /**
     * 查询调拨管理列表
     *
     * @param erpInventoryTransfer 调拨管理
     * @return 调拨管理
     */
    @Override
    public List<ErpInventoryTransfer> selectErpInventoryTransferList(ErpInventoryTransfer erpInventoryTransfer) {
        return erpInventoryTransferMapper.selectErpInventoryTransferList(erpInventoryTransfer);
    }

    /**
     * 新增调拨申请
     *
     * @param erpInventoryTransfer 调拨管理
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void insertErpInventoryTransfer(ErpInventoryTransfer erpInventoryTransfer) {
        erpInventoryTransferMapper.insertErpInventoryTransfer(erpInventoryTransfer);
        List<ErpInventoryTransferDetail> details = erpInventoryTransfer.getDetailList();
        if (details != null && !details.isEmpty()) {
            for (ErpInventoryTransferDetail detail : details) {
                detail.setStatus(0L);
                detail.setTransferId(erpInventoryTransfer.getId());
                detail.setInventoryId(erpInventoryTransfer.getDetailList().get(0).getId());
                erpInventoryTransferDetailMapper.insertErpInventoryTransferDetail(detail);
            }
        }
    }

    /**
     * 修改调拨管理
     *
     * @param erpInventoryTransfer 调拨管理
     * @return 结果
     */
    @Override
    public int updateErpInventoryTransfer(ErpInventoryTransfer erpInventoryTransfer) {
        return erpInventoryTransferMapper.updateErpInventoryTransfer(erpInventoryTransfer);
    }

    /**
     * 批量删除调拨管理
     *
     * @param ids 需要删除的调拨管理主键
     * @return 结果
     */
    @Override
    public int deleteErpInventoryTransferByIds(Long[] ids) {
        return erpInventoryTransferMapper.deleteErpInventoryTransferByIds(ids);
    }

    /**
     * 删除调拨管理信息
     *
     * @param id 调拨管理主键
     * @return 结果
     */
    @Override
    public int deleteErpInventoryTransferById(Long id) {
        return erpInventoryTransferMapper.deleteErpInventoryTransferById(id);
    }


    //    根据调拨单id查询调拨详细数据
    @Override
    public ErpInventoryTransfer selectErpInventoryTransferAndDetailById(Long Id) {
        List<ErpInventoryTransfer> erpInventoryTransfers = erpInventoryTransferMapper.selectErpInventoryTransferAndDetailById(Id);
        return erpInventoryTransfers.isEmpty() ? null : erpInventoryTransfers.get(0);
    }

    /**
     * 同意审核调拨
     *
     * @param erpInventoryTransfer
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int approveAllot(ErpInventoryTransfer erpInventoryTransfer) {
        //设置对象中审核人Id
        erpInventoryTransfer.setAuditorId(SecurityUtils.getLoginUser().getUser().getUserId());
        //改变调拨状态
        if (erpInventoryTransfer.getStatus() == 0) {
            erpInventoryTransfer.setStatus(1L);
        }
        //改变该调拨单中的所有要调拨物料的库存中的锁定数量
        erpInventoryTransfer.getDetailList().forEach(erpInventoryTransferDetail -> {
            //查询调拨详情信息中的  对应的库存信息
            ErpInventory erpInventory = erpInventoryMapper.selectErpInventoryById(erpInventoryTransferDetail.getInventoryId());
            BigDecimal targetQuantity = (erpInventoryTransferDetail.getPlanQuantity() == null) ? BigDecimal.ZERO : erpInventoryTransferDetail.getPlanQuantity();
            //将该物料的调拨数量增加到该物料在库存中的锁定数量
            erpInventory.setLockedQuantity(erpInventory.getLockedQuantity().add(targetQuantity));

            erpInventoryMapper.updateErpInventory(erpInventory);
        });
        //如果是跨仓库调拨
        if (!Objects.equals(erpInventoryTransfer.getFromWarehouseId(), erpInventoryTransfer.getToWarehouseId())) {

            //出库主表添加部分
            ErpOutboundOrder erpOutboundOrder = new ErpOutboundOrder();
            erpOutboundOrder.setOrderType(4L);  //设置调拨类型：4（调拨出库）
            erpOutboundOrder.setRelatedOrderNo(erpInventoryTransfer.getTransferNo());   //设置关联的调拨单号
            erpOutboundOrder.setWarehouseId(erpInventoryTransfer.getFromWarehouseId()); //设置出库的仓库id
            erpOutboundOrder.setStatus(1L); //设置出库单状态：1（已审核）
            erpOutboundOrder.setTotalQuantity(erpInventoryTransfer.getTotalQuantity()); //设置计划出库总数
            erpOutboundOrder.setOperatorId(erpInventoryTransfer.getOperatorId());    //设置操作人id
            erpOutboundOrder.setCheckerId(SecurityUtils.getLoginUser().getUser().getUserId());  //设置审核人id
            erpOutboundOrder.setCheckTime(new Date());  //设置审核时间为当前时间
            //添加出库主单
            erpOutboundOrderMapper.insertErpOutboundOrder(erpOutboundOrder);

            //入库主表添加部分
            ErpInboundOrder erpInboundOrder = new ErpInboundOrder();
            erpInboundOrder.setOrderType(4L);   //设置调拨类型：4（调拨入库）
            erpInboundOrder.setRelatedOrderNo(erpInventoryTransfer.getTransferNo()); //设置关联的调拨单号
            erpInboundOrder.setWarehouseId(erpInventoryTransfer.getToWarehouseId()); //设置入库的仓库id
            erpInboundOrder.setStatus(1L);     //设置入库单状态：1（已审核）
            erpInboundOrder.setTotalQuantity(erpInventoryTransfer.getTotalQuantity()); //设置计划入库总数
            erpInboundOrder.setOperatorId(erpOutboundOrder.getOperatorId());   //设置操作人id
            erpInboundOrder.setCheckerId(SecurityUtils.getLoginUser().getUser().getUserId());   //设置审核人id
            erpInboundOrder.setCheckTime(new Date());  //设置审核时间为当前时间
            //添加入库主单
            erpInboundOrderMapper.insertErpInboundOrder(erpInboundOrder);

            //出入库详表添加部分
            erpInventoryTransfer.getDetailList().forEach(erpInventoryTransferDetail -> {
                ErpOutboundOrderDetail erpOutboundOrderDetail = new ErpOutboundOrderDetail();
                ErpInboundOrderDetail erpInboundOrderDetail = new ErpInboundOrderDetail();

                //设置关联的出库单id
                erpOutboundOrderDetail.setOrderId(erpOutboundOrder.getId());
                //设置关联的入库单id
                erpInboundOrderDetail.setOrderId(erpInboundOrder.getId());

                //设置出库的物料id
                erpOutboundOrderDetail.setMaterialId(erpInventoryTransferDetail.getId());
                //设置入库的物料id
                erpInboundOrderDetail.setMaterialId(erpInventoryTransferDetail.getMaterialId());

                //设置该物料的计划出库数量
                erpOutboundOrderDetail.setPlanQuantity(erpInventoryTransferDetail.getPlanQuantity());
                //设置该物料的计划入库数量
                erpInboundOrderDetail.setPlanQuantity(erpInventoryTransferDetail.getPlanQuantity());

                //设置该出库物料的单位
                erpOutboundOrderDetail.setUnit(erpInventoryTransferDetail.getUnit());
                //设置该入库物料的单位
                erpInboundOrderDetail.setUnit(erpInventoryTransferDetail.getUnit());

                //设置该物料的来源仓库
                erpOutboundOrderDetail.setWarehouseId(erpOutboundOrderDetail.getWarehouseId());
                //设置该物料的目标仓库
                erpInboundOrderDetail.setWarehouseId(erpInboundOrderDetail.getWarehouseId());

                //设置该物料的来源库区
                erpOutboundOrderDetail.setAreaId(erpOutboundOrderDetail.getAreaId());
                //设置该物料的目标库区
                erpInboundOrderDetail.setAreaId(erpInboundOrderDetail.getAreaId());

                //设置该物料的出库状态：0（待出库）
                erpOutboundOrderDetail.setStatus(0L);
                //设置该物料的入库状态：0（待出库）
                erpInboundOrderDetail.setStatus(0L);

                //添加出库详细单
                erpOutboundOrderDetailMapper.insertErpOutboundOrderDetail(erpOutboundOrderDetail);
                //添加入库详细单
                erpInboundOrderDetailMapper.insertErpInboundOrderDetail(erpInboundOrderDetail);
            });

        }
        return erpInventoryTransferMapper.updateErpInventoryTransfer(erpInventoryTransfer);
    }

    /**
     * 拒绝审核调拨
     *
     * @param erpInventoryTransfer
     * @return
     */
    @Override
    public int refuseAllot(ErpInventoryTransfer erpInventoryTransfer) {
        //设置对象中审核人Id
        erpInventoryTransfer.setAuditorId(SecurityUtils.getLoginUser().getUser().getUserId());
        if (erpInventoryTransfer.getStatus() == 0) {
            erpInventoryTransfer.setStatus(2L);
        }
        return erpInventoryTransferMapper.updateErpInventoryTransfer(erpInventoryTransfer);
    }


}
